<style>
  .img { background: #fff; padding: 5px 5px 15px 5px; margin: 0 2px; border: 1px solid #666; display: inline-block; }
  .img img { cursor: pointer; }
  .pure_table_extra td { font-family: Lucida Sans Unicode !important; color: #666 !important; }
  .attrul { float: left; }
</style>

<?php 
$_SESSION[TINYMCE_UPLOAD] = 'upload/plugins/' . basename(dirname(__FILE__)) . '/';
if (!file_exists('../' . $_SESSION[TINYMCE_UPLOAD])) {
  Utils::create('../' . $_SESSION[TINYMCE_UPLOAD]);
}

$id = Utils::get_param('id', 0);
$opts = new stdClass();
$opts->cd = 't.id = :v1';
$opts->cdv = array(':v1' => $id);
$data = $orm->get('pb_ecom_product', NULL, NULL, NULL, NULL, $opts)->d;
$images = array();
$attrs = array();
$myopts = array();
$pdobjs = array();
if (count($data) > 0) {
  $opts = new stdClass();
  $opts->cd = 't.product_track_id = :v1';
  $opts->cdv = array(':v1' => $data[0]->track_id);
  $pdobjs = $orm->get('pb_ecom_product_obj', NULL, NULL, NULL, NULL, $opts)->d;
  $images = $orm->get('pb_ecom_product_img', NULL, NULL, NULL, NULL, $opts)->d;
  $attrs = $orm->get('pb_ecom_product_attr', NULL, NULL, NULL, NULL, $opts)->d;
  $myopts = $orm->get('pb_ecom_product_attr_opt', NULL, NULL, NULL, NULL, $opts)->d;
}

$pg = Utils::get_param('pg', 1);
$objs = $orm->get('pb_ecom_product', 't.name', 'ASC', $pg, SIZE, NULL);

$categories = $orm->get('pb_ecom_category', 't.name', 'ASC', NULL, NULL, NULL)->d;
$brands = $orm->get('pb_ecom_brand', 't.name', 'ASC', NULL, NULL, NULL)->d;
$tags = $orm->get('pb_ecom_tag', 't.name', 'ASC', NULL, NULL, NULL)->d;
$currs = $orm->get('pb_ecom_currency', 't.title', 'ASC', NULL, NULL, NULL)->d;
$members = $orm->get('pb_ecom_membership', 't.total_spent', 'ASC', NULL, NULL, NULL)->d;
?>

<div class="pure-form pure-form-aligned" style="padding: 10px; width: 830px;">
  <legend>Product</legend>

  <div class="pure-control-group">
    <label>Availability</label>
    <input id="avail" onclick="__data[0].status = (this.checked) ? 1 : 0; render_avail();" type="checkbox" checked="checked"/><label id="avail_txt" for="avail" style="text-align: center;">Available</label>
  </div>
  
  <div class="pure-control-group">
    <label>Name</label>
    <input id="name" type="text" class="pure-input-1-2" placeholder="{New Product}" />
  </div>
  
  <div class="pure-control-group">
    <label>Price</label>
    <select id="curr" onchange="render_member();"></select>
    <input id="price" onchange="render_member();" type="text" placeholder="{Price}" />
    <input type="checkbox" id="member" checked="checked" onclick="__data[0].enabled_member = this.checked ? 1 : 0; render_member();" /><label id="member_txt" for="member" style="width: 150px;">Member Discount</label>
  </div>
  
  <div class="pure-control-group" style="display: none; margin-bottom: 20px;">
    <label>&nbsp;</label>
    <div id="member_price" style="text-align: left; padding-left: 11em; margin-top: -20px;">&nbsp;</div>
  </div>
  
  <div class="pure-control-group">
    <label>Attributes & Options (e.g. Color: B, W)<button class="pure-button" onclick="set_attr(null, event);">Add</button></label>
    <div id="attrs" style="text-align: left; padding-left: 11em; margin-top: -60px; min-height: 90px; vertical-align: top;">&nbsp;</div>
  </div>
  
  <div class="pure-control-group" style="clear: both;">
    <label><input type="checkbox" id="stock" checked="checked" onclick="__data[0].enabled_stock = this.checked ? 0 : 1; render_pdobjs();" /><label id="stock_txt" for="stock">Unlimited Stock</label></label>
    <div id="objs" style="text-align: left; padding-left: 11em; margin-top: -30px; min-height: 60px; clear: both;">&nbsp;</div>
  </div>
  
  <div class="pure-control-group" style="clear: both;">
    <label>Images (512k or less)<span  id="uploader"></span></label>
    <div id="images" style="text-align: left; padding-left: 11em; margin-top: -20px; min-height: 60px;">&nbsp;</div>
  </div>
  
  <div class="pure-control-group">
    <label>Weight (kg)</label>
    <input id="weight" type="text" class="pure-input-1-2" placeholder="{Weight e.g. 0.58}" />
  </div>
  
  <div class="pure-control-group">
    <label>Category</label>
    <select id="category" style="min-width: 250px;">
      <option value="0">Select...</option>
    </select>
  </div>
  
  <div class="pure-control-group">
    <label>Brand</label>
    <select id="brand" style="min-width: 250px;">
      <option value="0">Select...</option>
    </select>
  </div>
  
  <div class="pure-control-group">
    <label>Tags</label>
    <div id="tags" style="text-align: left; padding-left: 11em; margin-top: -1.5em; min-height: 30px;">&nbsp;</div>
  </div>
  
  <div class="pure-control-group">
    <label>Brief</label>
    <label><textarea id="brief" style="width: 700px; resize: none; "></textarea></label>
  </div>
  
  <div class="pure-control-group">
    <label>Description</label>
    <label><textarea id="tinymce" style="width: 700px; height: 500px;"></textarea></label>
  </div>
  
  <div class="pure-control-group">
    <label>&nbsp;</label>
    <button class="pure-button pure-input-1-2 pure-button-primary" onclick="submit_obj();">Save</button>
  </div>
  
  <div class="pure-control-group expg">
    <label>&nbsp;</label>
    <button id="del_obj" class="pure-button" onclick="delete_obj();">Delete</button>
    <button id="new_obj" class="pure-button" onclick="__data = []; __images = []; __attrs = []; __opts = []; __pdobjs = []; reset(); render();">New Product</button>
  </div>
</div>

<div id="dialog_attr" class="pure-form" style="display: none;" title="Attribute (e.g. Color)">
  <input type="text" id="name_attr" style="width: 100%;"></input>
</div>

<div id="dialog_opt" class="pure-form" style="display: none;" title="Option (e.g. Black, White)">
  <input type="text" id="name_opt" style="width: 100%;"></input>
</div>

<script type="text/javascript">
  /*<![CDATA[*/
  var __categories = JSON.parse('<?php echo addslashes(json_encode($categories)); ?>');
  var __categories_root = Utils.get_root(__categories);
  var __brands = JSON.parse('<?php echo addslashes(json_encode($brands)); ?>');
  var __tags = JSON.parse('<?php echo addslashes(json_encode($tags)); ?>');
  var __currs = JSON.parse('<?php echo addslashes(json_encode($currs)); ?>');
  var __members = JSON.parse('<?php echo addslashes(json_encode($members)); ?>');
  var __attrs = JSON.parse('<?php echo addslashes(json_encode($attrs)); ?>');
  var __opts = JSON.parse('<?php echo addslashes(json_encode($myopts)); ?>');
  var __pdobjs = JSON.parse('<?php echo addslashes(json_encode($pdobjs)); ?>');
  var __images = JSON.parse('<?php echo addslashes(json_encode($images)); ?>');
  var __objs = JSON.parse('<?php echo addslashes(json_encode($objs)); ?>');
  var __data = JSON.parse('<?php echo addslashes(json_encode($data)); ?>');
  var __dir = '<?php echo PLGN_DIR . basename(dirname(__FILE__)); ?>';
  var __file = '<?php echo addslashes($app_data->param_file); ?>';
  var __requrl = '<?php echo Utils::get_requrl($app_data); ?>';
  var __redmd = '<?php echo addslashes($app_data->sys->redmd); ?>';
  var __sys = '<?php echo addslashes($app_data->sys->php_name); ?>';
  var __id = '<?php echo $app_data->param_id; ?>';
  var __session_id = '<?php echo session_id(); ?>';
  
  $(function(){
    reset();
    
    $('#avail').button();
    $('#member').button();
    $('#stock').button();

    for (var idx in __currs) {
      var itm = __currs[idx];
      $('#curr').append('<option value="' + itm.title + '" ' + ((itm.is_default == 1) ? 'selected="selected"' : '') + '>' + itm.title + '</option>');
    }

    init_category(__categories_root, '');
    
    for (var idx in __brands) {
      var itm = __brands[idx];
      $('#brand').append('<option value="' + itm.id + '">&nbsp;' + itm.name + '</option>');
    }
    
    for (var idx in __tags) {
      var itm = __tags[idx];
      $('#tags').append('<input onclick="update_tags();" type="checkbox" id="tag_' + itm.id + '" /><label id="tag_txt_' + itm.id + '" for="tag_' + itm.id + '" style="margin-right: 0;" title="' + itm.name + '">' + Utils.get_short(itm.name, 10) + '</label>');
    }
    $('#tags').buttonset();

    $('#tinymce').val(__data[0].description);
    tinyMCE.init( {
      // General options
      mode: 'exact',
      elements: 'tinymce',
      theme: 'advanced',

      plugins: 'filebrowser,style,iespell,preview,media,wordcount,inlinepopups',
      // Theme options
      theme_advanced_buttons1: 'undo,redo,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,fontselect,fontsizeselect,|,forecolor,backcolor,|,image,media,|,preview',
      theme_advanced_buttons2: '',
      theme_advanced_buttons3: '',
      theme_advanced_toolbar_location: 'top',
      theme_advanced_toolbar_align: 'left',
      theme_advanced_statusbar_location: 'bottom',
      theme_advanced_resizing: true,

      file_browser_callback: 'filebrowser',

      theme_advanced_resize_horizontal: false,
      
      // Example content CSS (should be your site CSS)
      theme_advanced_font_sizes: '10px,11px,12px,13px,14px,15px,16px,17px,18px,19px,20px,21px,22px,23px,24px,25px,26px,27px,28px,29px,30px',
    });
    
    render();

    Upload.init(
      'uploader', 
      __requrl + 'upload_images', 
      function(rslt, srv_err) {
        __images = __images.concat(rslt);
        render_images();
      }, 
      {
        file_size_limit: '10MB',
        upload_start_handler: function(file) {
          this.setPostParams({
            PHPSESSID: __session_id,
            track_id: __data[0].track_id
          });
        },
        debug: 0
      }
    );
  });

  function init_category(node, prefix) {
    if (node.id != 0) {
      $('#category').append('<option value="' + node.id + '">' + ((prefix == '') ? '' : prefix + ') ') + node.name +'</option>');
    }
    for (var idx in node.__c) {
      var itm = node.__c[idx];
      init_category(itm, ((prefix == '') ? '(' : '\u2002' + prefix + '-') + (parseInt(idx, 10) + 1));
    }
  };

  function reset() {
    if (__data.length == 0) {
      __data[0] = {
        id: 0,
        track_id: Utils.unique(),
        name: '',
        curr: '',
        price: 0.00,
        weight: 0.00,
        enabled_member: 0,
        enabled_stock: 1,
        category_id: 0,
        brand_id: 0,
        tag_id: '',
        brief: '',
        description: '',
        stock: 0,
        stock_alert: 0,
        status: 1,
        sold__: 0,
        alert__: 0
      };
    }
    __pdobjs = __pdobjs.sort(function(a, b) {
      return a.attr_opt_code.localeCompare(b.attr_opt_code);
    });
    Utils.set_attrs(__attrs, __opts);
  };

  function render() {
    Utils.leftbar(
      __objs,
      __data[0].id,
      'Products',
      'name',
      function(page) {
        Url.redirect(__redmd, __sys + '.php?i=' + __id + '&__file=' + __file + '&id=' + __data[0].id + '&pg=' + page);
      }
    );
    render_data();
  };

  function render_data() {
    Url.insert_param('id', __data[0].id);
    
    $('#name').val(__data[0].name);
    $('#price').val(__data[0].price);
    $('#weight').val(__data[0].weight);
    $('#brand').val(__data[0].brand_id);
    $('#category').val(__data[0].category_id);
    $('#brief').val(__data[0].brief);
    if (__data[0].curr != '') {
      $('#curr').val(__data[0].curr);
    }
    if (tinyMCE.get('tinymce')) {
      tinyMCE.get('tinymce').setContent(__data[0].description);
    } else {
      $('#tinymce').val(__data[0].description);
    }
    
    render_avail();
    render_member();
    render_attrs();
    render_pdobjs();
    render_tags();
    render_images();
    
    if (__data[0].id != 0) {
      $('.expg').show();
    } else {
      $('.expg').hide();
    }
  };

  function render_attrs() {
    $('#attrs').empty();
    for (var idx in __attrs) {
      var itm = __attrs[idx];
      $('#attrs').append(
        '<div class="wrapper-dropdown-3">' +
          '<div class="main">' +
            '<a href="#">' +
              '<i class="fa fa-times" onclick="delete_attr(' + itm.id + ');"></i>' +
              '<i class="fa fa-pencil" onclick="set_attr(' + itm.id + ', event);"></i>' +
              '<i class="fa fa-plus" onclick="set_opt(null, ' + itm.id + ', event);"></i>' +
              itm.name +
            '</a>' +
          '</div>' +
          ((itm.__opts.length > 0) ? '<ul id="attr_' + itm.id + '" class="dropdown" style="position: relative"></ul>' : '') +
        '</div>'
      );
      for (var idx2 in itm.__opts) {
        var itm2 = itm.__opts[idx2];
        $('#attr_' + itm.id).append(
          '<li>' +
            '<a href="#">' +
              '<i class="fa fa-times" onclick="delete_opt(' + itm2.id + ');"></i>' +
              '<i class="fa fa-pencil" onclick="set_opt(' + itm2.id + ', ' + itm.id + ', event);"></i>' +
              itm2.name +
            '</a>' +
         '</li>'
        );
      }
    }
  };

  function render_pdobjs() {
    if (__data[0].enabled_stock == 1) {
      $('#stock')[0].checked = false;
      $('#stock_txt').empty();
      $('#stock_txt').append('<span class="ui-button-text">Limited Stock</span>');
      $('#stock_txt').removeClass('ui-state-active');
      
    } else {
      $('#stock')[0].checked = true;
      $('#stock_txt').empty();
      $('#stock_txt').append('<span class="ui-button-text">Unlimited Stock</span>');
      $('#stock_txt').addClass('ui-state-active');
    }
    
    $('#objs').empty();
    
    if (__pdobjs.length > 0) {
      $('#objs').append('<table cellpadding="0" cellspacing="0" class="pure-table pure_table_extra"><thead><tr id="obj_head"></tr></thead><tbody id="obj_body"></tbody></table>');
      $('#obj_head').append('<th style="min-width: 120px;">Item</th>');
      if (__data[0].enabled_stock == 1) {
        $('#obj_head').append('<th style="min-width: 40px;">Current Stock</th>');
        $('#obj_head').append('<th style="width: auto; min-width: 80px;">Alert if less than</th>');
      }
      $('#obj_head').append('<th style="width: auto; min-width: 80px;">+/-$</th>');
      for (var idx in __pdobjs) {
        var itm = __pdobjs[idx];
        $('#obj_body').append(
          '<tr class="' + ((idx % 2 == 0) ? 'pure-table-even' : 'pure-table-odd') + '">' + 
            '<td>' + itm.attr_opt_code + '</td>' +
            ((__data[0].enabled_stock == 1) ? '<td><input onchange="__pdobjs[' + idx + '].stock = this.value; render_pdobjs();" type="text" placeholder="{Stock}" value="' + itm.stock + '" ' + ((parseFloat(itm.stock, 10) <= parseFloat(itm.stock_alert, 10) && itm.stock_alert != 0) ? 'style="color: #ff0000;"' : '') + '/></td>' : '') +
            ((__data[0].enabled_stock == 1) ? '<td><input onchange="__pdobjs[' + idx + '].stock_alert = this.value; render_pdobjs();" type="text" placeholder="{Stock}" value="' + itm.stock_alert + '" /></td>' : '') +
            '<td><input onchange="__pdobjs[' + idx + '].price = this.value;" type="text" placeholder="{Stock}" value="' + itm.price + '" /></td>' +
          '</tr>'
        );
      }
      if (__members.length == 0) {
        $('#m_body').append('<tr><td colspan="' + $('#m_head')[0].cells.length + '">None</td></tr>');
      }
    } else {
      if (__data[0].enabled_stock == 1) {
        $('#objs').append('<div><input id="pdstock" onchange="__data[0].stock = this.value; render_pdobjs();" type="text" placeholder="{Stock}" value="' + __data[0].stock + '" ' + ((parseFloat(__data[0].stock, 10) <= parseFloat(__data[0].stock_alert, 10) && __data[0].stock_alert != 0) ? 'style="color: #ff0000;"' : '') + '/>&nbsp;&nbsp;&nbsp;Alert if Less than&nbsp;<input  id="pdstock_alert" onchange="__data[0].stock_alert = this.value; render_pdobjs();" type="text" placeholder="{Alert if less than}" value="' + __data[0].stock_alert + '" />&nbsp;(0 means no alert)');
      }
    }
  };

  function render_images() {
    $('#images').empty();
    for (var idx in __images) {
      var itm = __images[idx];
      $('#images').append(
          '<table cellpadding=0 cellspacing=0 class="img">' +
            '<tr><td style="text-align: right;"><img onclick="set_image_default(' + itm.id + ');" src="' + __dir + ((itm.is_default == 0) ? '/images/nodef.png' : '/images/def.png' ) + '"></img><img onclick="delete_image(' + itm.id + ');" src="' + __dir + '/images/del.png"></img></td></tr>' +
            '<tr><td><a rel="prettyPhoto[gallery1]" href="' + itm.file + '"><img style="height: 40px;" src="' + itm.file + '"></img></a></td></tr>' +
          '</table>');
    }
    $("a[rel^='prettyPhoto']").prettyPhoto({
      social_tools: ''
    });
  };

  function render_avail() {
    if (__data[0].status == 1) {
      $('#avail')[0].checked = true;
      $('#avail_txt').empty();
      $('#avail_txt').append('<span class="ui-button-text">Available</span>');
      $('#avail_txt').addClass('ui-state-active');
    } else {
      $('#avail')[0].checked = false;
      $('#avail_txt').empty();
      $('#avail_txt').append('<span class="ui-button-text">Unavailable</span>');
      $('#avail_txt').removeClass('ui-state-active');
    }
  };

  function render_member() {
    if (__data[0].enabled_member == 1) {
      $('#member')[0].checked = true;
      $('#member').button( "option", "icons", { primary: "ui-icon-circle-check" } );
      $('#member_txt').addClass('ui-state-active');
      $('#member_price').parent().show();
      $('#member_price').empty();
      $('#member_price').append('<table cellpadding="0" cellspacing="0" class="pure-table pure_table_extra"><thead><tr id="m_head"></tr></thead><tbody id="m_body"></tbody></table>');

      $('#m_head').append('<th style="min-width: 120px;">&nbsp;</th>');
      $('#m_head').append('<th style="min-width: 40px;">-%</th>');
      $('#m_head').append('<th style="width: auto; min-width: 80px;">' + $('#curr').val() + '</th>');
      $('#m_head').append('<th style="width: auto; min-width: 80px;">-$</th>');
      for (var idx in __members) {
        var itm = __members[idx];
        var prc = $('#price').val() * (1 - (itm.discount / 100));
        var dis = $('#price').val() * (itm.discount / 100);
        $('#m_body').append(
          '<tr class="' + ((idx % 2 == 0) ? 'pure-table-even' : 'pure-table-odd') + '">' + 
            '<td>' + itm.title + '</td>' +
            '<td>' + accounting.toFixed(itm.discount, 2) + '%</td>' +
            '<td>' + accounting.formatMoney(prc) + '</td>' +
            '<td style="color: #ff0000 !important;">-' + accounting.formatMoney(dis) + '</td>' +
          '</tr>'
        );
      }
      if (__members.length == 0) {
        $('#m_body').append('<tr><td colspan="' + $('#m_head')[0].cells.length + '">None</td></tr>');
      }
    } else {
      $('#member')[0].checked = false;
      $('#member').button( "option", "icons", { primary: "ui-icon-circle-close" } );
      $('#member_txt').removeClass('ui-state-active');
      $('#member_price').parent().hide();
    }
  };

  function render_tags() {
    $('#tags input[type=checkbox]').button( "option", "icons", { primary: "ui-icon-closethick" } );
    $('#tags input[type=checkbox]').prop('checked', false);
    $('#tags label').removeClass('ui-state-active');

    if (__data[0].tag_id != '') {
      var tmp = __data[0].tag_id.substr(1, __data[0].tag_id.length - 2).split(',');
      for (var idx in tmp) {
        var itm = tmp[idx];
        if (itm == '') {
          continue;
        }
        $('#tag_' + itm).button( "option", "icons", { primary: "ui-icon-check" } );
        $('#tag_' + itm).prop('checked', true);
        $('#tag_txt_' + itm).addClass('ui-state-active');
      }
    }
  };

  function update_tags() {
    __data[0].tag_id = ',';
    var tmp = $('#tags input[type="checkbox"]:checked');
    for (var idx in tmp) {
      var itm = tmp[idx];
      if (!itm.id) {
        continue;
      }
      __data[0].tag_id += itm.id.replace('tag_', '') + ',';
    }
    render_tags();
  };

  function submit_obj() {
    req = __data[0];
    req.name = $('#name').val();
    req.curr = $('#curr option:selected').text();
    req.price = $('#price').val();
    req.enabled_member = $('#member').is(':checked') ? 1 : 0;
    req.weight = $('#weight').val();
    req.brief = $('#brief').val();
    req.description = tinyMCE.get('tinymce').getContent();
    req.brand_id = $('#brand option:selected').val();
    req.category_id = $('#category option:selected').val();
    req.__pdobjs = __pdobjs;
    req.__pg = __objs.p;

    if (req.__pdobjs.length == 0) {
      req.stock = $('#pdstock').val();
      req.stock_alert = $('#pdstock_alert').val();
      req.alert__ = (req.stock <= req.stock_alert && req.stock_alert != 0) ? 1 : 0;
    } else {
      req.stock = 0;
      req.alert__ = 0;
      for (var idx in __pdobjs) {
        var itm = __pdobjs[idx];
        req.stock += parseInt(itm.stock, 10);
        if (itm.stock <= itm.stock_alert && itm.stock_alert != 0) {
          req.alert__ = 1;
        }
      }
    }
    Ajax.request(
      __requrl + 'submit_obj',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        if (rslt.__objs) {
          __objs = rslt.__objs;
          delete rslt.__objs;
        }
        __data = [ rslt ];
        render();
      },
      null
    );
  };

  function set_image_default(id) {
    for (var idx in __images) {
      var obj = __images[idx];
      obj.is_default = 0;
    }
    var req = Utils.get_by_id(id, __images);
    req.is_default = 1;
    
    Ajax.request(
      __requrl + 'set_image_default',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        render_images();
      },
      null
    );
  };

  function delete_image(id) {
    var req = Utils.get_by_id(id, __images);
    Ajax.request(
      __requrl + 'delete_image',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        __images = rslt;
        render_images();
      },
      { confirm: 1 }
    );
  };
  
  function delete_obj() {
    Ajax.request(
      __requrl.replace(__file, 'index') + 'delete_obj',
      'req=' + Utils.encodeURI(JSON.stringify(__data[0])),
      function(rslt) {
        Url.redirect(__redmd, __sys + '.php?i=' + __id);
      },
      { confirm: 1 }
    );
  };

  function delete_attr(id) {
    var req = Utils.get_by_id(id, __attrs);
    Ajax.request(
      __requrl + 'delete_attr',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        Utils.splice_by_id(id, __attrs);
        __pdobjs = rslt.__pdobjs;
        delete rslt.__pdobjs;
        render_attrs();
        render_pdobjs();
      },
      { confirm: 1 }
    );
  };

  function delete_opt(id) {
    var req = Utils.get_by_id(id, __opts);
    for (var idx in __attrs) {
      var itm = __attrs[idx];
      if (itm.id == req.product_attr_id && itm.__opts.length == 1) {
        alert('Can\'t delete last option');
        return;
      }
    }
    Ajax.request(
      __requrl + 'delete_opt',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        Utils.splice_by_id(id, __opts);
        __pdobjs = rslt.__pdobjs;
        delete rslt.__pdobjs;
        reset();
        render_attrs();
        render_pdobjs();
      },
      { confirm: 1 }
    );
  };

  function get_obj(id) {
    var req = {
      id: id
    };
    Ajax.request(
      __requrl + 'get_obj',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        __data = rslt;
        __images = __data[0].__images;
        __attrs = __data[0].__attrs;
        __opts = __data[0].__opts;
        __pdobjs = __data[0].__pdobjs;
        delete __data[0].__images;
        delete __data[0].__attrs;
        delete __data[0].__opts;
        delete __data[0].__pdobjs;
        reset();
        render();
      },
      null
    );
    return false;
  };

  function set_attr(id, ev) {
    var func = function() {
      var req = Utils.get_by_id(id, __attrs);
      req = (req) ? req : { product_track_id: __data[0].track_id };
      req.name = $('#name_attr').val();
      Ajax.request(
        __requrl + 'submit_attr',
        'req=' + Utils.encodeURI(JSON.stringify(req)),
        function(rslt) {
          __pdobjs = rslt.__pdobjs;
          delete rslt.__pdobjs;
          if (!req.id) {
            __opts.push(rslt.__opt);
            delete rslt.__opt;
            __attrs.push(rslt);
          }
          reset();
          render_attrs();
          render_pdobjs();
          $('#dialog_attr').dialog('close');
        },
        null
      );
    };
    
    $('#dialog_attr').dialog({
      position: {
        my: 'left+0 bottom+0',
        of: ev.target
      },
      buttons: {
        'OK': function() {
          func();
        },
        'Cancel': function() { 
          $(this).dialog('close');
        }
      }
    });
    
    $('#name_attr')[0].onkeypress = function(ev) {
      if(ev.which == 13) {
        func();
      }
    };

    $('#name_attr').val('');
    var obj = Utils.get_by_id(id, __attrs);
    if (obj) {
      $('#name_attr').val(obj.name);
      $('#name_attr').select();
    }
  };

  function set_opt(id, attr_id, ev) {
    var func = function() {
      var req = Utils.get_by_id(id, __opts);
      req = (req) ? req : { product_track_id: __data[0].track_id, product_attr_id: attr_id };
      req.name = $('#name_opt').val();
      Ajax.request(
        __requrl + 'submit_opt',
        'req=' + Utils.encodeURI(JSON.stringify(req)),
        function(rslt) {
          __pdobjs = rslt.__pdobjs;
          delete rslt.__pdobjs;
          if (!req.id) {
            __opts.push(rslt);
          }
          reset();
          render_attrs();
          render_pdobjs();
          $('#dialog_opt').dialog('close');
        },
        null
      );
    };
    
    $('#dialog_opt').dialog({
      position: {
        my: 'left+0 bottom+0',
        of: ev.target
      },
      buttons: {
        'OK': function() {
          func();
        },
        'Cancel': function() { 
          $(this).dialog('close');
        }
      }
    });
    
    $('#name_opt')[0].onkeypress = function(ev) {
      if(ev.which == 13) {
        func();
      }
    };

    $('#name_opt').val('');
    var obj = Utils.get_by_id(id, __opts);
    if (obj) {
      $('#name_opt').val(obj.name);
      $('#name_opt').select();
    }
  };
  /*]]>*/
</script>